package com.lanju.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.lanju.entity.User;
import com.lanju.model.ResultModel;
import com.lanju.service.JedisService;
import com.lanju.service.UserService;
import com.lanju.util.SecurityContext;
import com.lanju.util.ServletUtil;

@Controller
@RequestMapping("/user")
public class UserController {
    
	private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
	
    
    @Autowired
    UserService userService;
    @Resource
	JedisService jedisService;
    
    @RequestMapping("/add")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel add(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		User user = json.toJavaObject(User.class);
        return  userService.add(user);
    }
    
    @RequestMapping("/del")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel del(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		User user = json.toJavaObject(User.class);
        return  userService.del(user);
    }
    
    @RequestMapping("/edit")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel edit(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		User user = json.toJavaObject(User.class);
        return  userService.edit(user);
    }
    
    /** 根据userid查询用户 */
    @RequestMapping("/getById")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public User getById(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		User user = json.toJavaObject(User.class);
        return  userService.getById(user.getUserId());
    }
    
    /** 根据手机号码获取用户 */
    @RequestMapping("/getByPhone")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public User getByPhone(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
        return  userService.getByPhone(param);
    }
    
    /** 根据微信openid获取用户 */
    @RequestMapping("/getByOpenId")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public User getByOpenId(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
        return  userService.getByOpenId(param);
    }
    
    /** 获取用户列表 */
    @RequestMapping("/getList")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Map<String, Object> getList(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		User user = json.toJavaObject(User.class);
        return  userService.getList(user, (int)param.get("pageSize"), (int)param.get("offset"));
    }

    /** 检验该手机号是否存在 */
    @RequestMapping("/checkPhone")
    @ResponseBody
    public ResultModel checkPhone(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
        User u =  userService.getByPhone(param);
        if(u!=null){
            return ResultModel.fail("该手机号码已被注册", 1);
        }
        return ResultModel.success("号码可用", 0);
    }
    
    /** 注册账号
     *  @param phone: 手机号码,   password: 密码,   captcha: 验证码
     */
    @RequestMapping("/regist")
    @ResponseBody
    public ResultModel regist(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
        return userService.regist(param, request);
    }
    
    /**
     * 找回密码
     * */
    @RequestMapping("/findPassword")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel findPassword(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
        return  userService.findPassword(param);
    }
    
    /** 获取我的管家 */
    @RequestMapping("/getMyGuanJia")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel getMyGuanJia(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		User user =(User) session.getAttribute("userModel");
		param.put("userId", user.getUserId());
        return  userService.getMyGuanJia(param);
    }
    /**
     * 是否登录
     * @return
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("/isLogin")
    @ResponseBody
    public Map<String,Object> isLogin(HttpServletRequest request,HttpSession session,HttpServletResponse response) throws ClientProtocolException, IOException{
    	User user=(User)session.getAttribute("userModel");
    	Map<String,Object> result=new HashMap<String, Object>();
    	Map<String, Object> param = ServletUtil.getParameterMap(request);
    	System.out.println("保存的sessionid是："+session.getId());
		System.out.println("保存的session的值是："+session.getAttribute("userModel"));
    	if(user ==null){
    		LOGGER.info("is not login");
//			WeiXinInterfaceController weixinInf=new WeiXinInterfaceController();
//			weixinInf.Login(request, response);
    		result.put("success", false);
    		result.put("msg", "您还没登录，请登录再操作吧");
    	}else{
    		System.out.println(user+"==="+user.getPhone());
    		result.put("user",user);
    		result.put("success", true);
    		result.put("msg", "已登录");
    	}
    	 return result;
    }
    
	@RequestMapping("/queryUserByOpenid")
    @ResponseBody
    public Map<String,Object> queryUserByOpenid(HttpServletRequest request,HttpSession session){
		Map<String,Object> result=new HashMap<String, Object>();
    	Map<String, Object> param = ServletUtil.getParameterMap(request);
    	 User user =(User) session.getAttribute("userModel");
    	 if(StringUtils.isEmpty(param.get("openid"))){
    		 LOGGER.info("is not login");
    		 result.put("success", false);
    	 }else if((!StringUtils.isEmpty(param.get("openid").toString())) && StringUtils.isEmpty(user) ){
    		 LOGGER.info(param.get("phone").toString()+" local not exits user="+user);
    		 Map<String, Object> map= jedisService.getMap(param.get("openid").toString(), "nickName","userId","headImg","openId","phone","bills","sex","status","flag");
    		 if(map==null){ 
 				result.put("success", false);
 				result.put("msg", "您还没登录，请登录再操作吧");
 			}else{
 				List<String> list= (List<String>) map.get("rows");
 				User userModel=new User();
 				result.put("success", true);
 				userModel.setHeadImg(list.get(2));
 				userModel.setFlag(Integer.valueOf(list.get(8).toString()));
 				userModel.setNickName(list.get(0));
 				userModel.setUserId(list.get(1));
 				userModel.setOpenId(list.get(3));
 				userModel.setSex(Integer.valueOf(list.get(6)));
 				userModel.setStatus(Integer.valueOf(list.get(7)));
 				SecurityContext.saveUserToSeesion(userModel, request.getSession());
 				SecurityContext.setUser(userModel);
 				result.put("user",userModel);
 			}
    	 }else if(user !=null){
    		 LOGGER.info(param.get("phone").toString()+"user is exits user="+user);
    		 result.put("user",user);
    		 result.put("success", true);
    	 }
		return result;
    }
	
	@RequestMapping("/getUserAuthInfo")
    @ResponseBody
	public Map<String,Object> getUserAuthInfo(HttpServletRequest request,HttpSession session){
		 User user =(User) session.getAttribute("userModel");
		 Map<String,Object> result=new HashMap<String, Object>();
		 if(user !=null ){
			 result.put("idCard", user.getIdCard());
			 result.put("phone", user.getPhone()); 
		 }else{
			 result.put("idCard",false);
		 }
		return result;
	}
	
	@RequestMapping("/updateUserInfo")
    @ResponseBody
	public Map<String,Object> updateUserInfo(HttpServletRequest request,HttpSession session,@RequestParam(value = "headImg", required = false) MultipartFile headImg){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		if(headImg != null ){
			String fileUrl=ImageOptController.filesUpload(headImg, "userInfo");
			param.put("url", fileUrl);
		}
		return userService.updateUserInfo(param,session);
	}
	
	
}
